<?php
    require_once("include/common.php");

    $id = $_GET['id'] ?? '' ;
    $virtual = $_GET['virtual'] ?? false ;
?>

<!DOCTYPE html>
<html lang="en" ng-app="deviceApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

<title>表计列表</title>

    <?php
        require_once("pages/resources.php");
    ?>
 
<!--     <link href="/meter/resources/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet"> -->

    <script src="/meter/resources/jquery/jquery-2.0.3.js"></script>
    
    <script src="/meter/resources/angular-1.5.5/angular.js"></script>
    <script src="/meter/resources/js-base-util.js"></script>
    <script type="text/javascript" src="/meter/resources/layer/layer.js"></script>
    <script type="text/javascript" src="/meter/resources/js/tags.min.js"></script> 
 
</head>
<body  id="deviceCtrl" ng-controller="deviceCtrl">

  
    <!-- Page container -->
    <div class="page-container">

                 
         <!-- Page tabs -->
        <div class="tabbable page-tabs" style ="margin-bottom: 10px">
            <ul class="nav nav-tabs" style1="margin-bottom: 10px">
                    <li class="active"><a href="tables_static.html#base_info" data-toggle="tab"><i class="icon-table2"></i> 基本属性 </a></li>
                    <?php if($virtual) { ?>
                    <li><a href="#meters" data-toggle="tab"><i class="icon-checkbox-partial"></i> 关联电表 </a></li>
                    <?php } ?>
            </ul>
            <span id="responseId" class="label ">
                success!
            </span>
            <div class="tab-content">

                <!-- First tab -->
                <div class="tab-pane active fade in" id="base_info">

                        <!--   -->
                        <div class="panel panel-default">
                 
                            <!-- Form begin -->
                            <form class="form-horizontal" role="form" ng-submit="save();">
                                <div class="panel panel-default">
                                    
                                    <div class="panel-body">
                                   
                                        <div class="form-group  ">
                                            <label class="col-sm-2 control-label"> ID :</label>
                                            <div class="col-sm-4">
                                                <input type="text" class="form-control" id="_INPUT_METERID" ng-model="meter._METER"  
                                                 <?php 
                                                 if( $id ){
                                                    print('readonly="readonly"');   
                                                 }
                                                 
                                                 ?>
                                                 >  
                                            </div>
                                            
                                            
                                        
                                        </div>
                                        <div class="form-group  ">
                                            <label class="col-sm-2 control-label"> NAME :</label>
                                                <div class="col-sm-4">
                                                    <input type="text" class="form-control" id="_INPUT_NAME" ng-model="meter._NAME" >  
                                                </div>
                                        </div>

                                        <div class="form-group">
                                            <label class="col-sm-2 control-label"> User :  </label>
                                            <div class="col-sm-4">
                                                <input type="text" class="form-control" id="_INPUT_USER"  readonly="readonly" value="{{meter._USERID}}" >  
                                            </div>
                                        </div>  


                                        <div class="form-group">
                                            <label class="col-sm-2 control-label"> Type:  </label>
                                            <div class="col-sm-4">
                                                <input type="text" class="form-control" id="_INPUT_METERTYPE"  readonly="readonly" value="{{getMeterType(meter._METERTYPE)}}" >  
                                            </div>
                                        </div>  

                                        <div class="form-group">

                                                <label class="col-sm-2 control-label">Tags:</label>
                                                <div class="col-sm-10">
                                                    <input type="text" id="tags" class="tags"  value="">
                                                </div>

                                                
                                        </div>  

                                               
                                        <div class="form-group  ">
                                            <label class="col-sm-2 control-label"> Updated :</label>
                                            <div class="col-sm-4">
                                                <input type="text" class="form-control" value="{{meter._UPDATED}}" readonly="">  
                                            </div>
                                            
                                            <label class="col-sm-2 control-label"> Synced :</label>
                                            <div class="col-sm-4">
                                                <input type="text" class="form-control" value="{{meter._SYNC}}" readonly="">  
                                            </div>
                                 
                                        </div>   

                                           

                                        <div class="form-actions text-right">
                                            <input type="submit" value="Save"   class="btn btn-primary">
                                        </div>

                                    </div>
                                </div>
                            </form>
                                     
                        <!-- form end -->
                                <!-- form end -->
                            
                        </div>
                        <!-- /default table -->
                </div> <!-- endof first table -->
                
                <?php if($virtual) { ?>
                <!-- second tab -->
                <div class="tab-pane   fade in" id="meters">

                    <!-- Default table -->
                    <div class="panel panel-default">
                             
                        <div class="table-responsive">       
                            <!-- Form begin -->
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th class="col-md-2">CODE</th>
                                        
                                        <th class="col-md-2">NAME</th>
                                       
                                        <th class="col-md-2">操作</th>
                                       
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr ng-repeat="m in meters">
                                        
                                        
                                        <td>
                                            {{m._METER }}
                                        </td>
                                        <td>
                                            {{m._NAME }}
                                           
                                        </td>                                       
                                        
                                        <td>
                                            <!-- 
                                            <center>
                                              <a href="#" ng-click1="removeParameter(p.id   )" title="删除租户">
                                                    <i class="icon-remove"></i>
                                                </a> 
                                            </center>  
                                            -->
                                        </td>
                                        
                                    </tr>
                                     
     
                                </tbody>
                            </table>
                            <!-- form end -->
                        </div>    

                        
                            
                    </div>

                    
                     
                </div> <!-- endof second tab -->
                <?php } ?>
            </div> <!-- end of tab-content -->

        </div>                

    </div>
              
     

</body>
<script type="text/javascript">

var app = angular.module("deviceApp", [], function ($httpProvider) {  
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";  
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';  
    var param = function (obj) {  
        var query = "", name, value, fullSubName, subName, subValue, innerObj, i;  
        for (name in obj) {  
            value = obj[name];  
            if (value instanceof Array) {  
                for (i = 0; i < value.length; ++i) {  
                    subValue = value[i];  
                    fullSubName = name + "[" + i + "]";  
                    innerObj = {};  
                    innerObj[fullSubName] = subValue;  
                    query += param(innerObj) + "&";  
                }  
            } else if (value instanceof Object) {  
                for (subName in value) {  
                    subValue = value[subName];  
                    fullSubName = name + "[" + subName + "]";  
                    innerObj = {};  
                    innerObj[fullSubName] = subValue;  
                    query += param(innerObj) + "&";  
                }  
            } else if (value !== undefined && value !== null) {  
                query += encodeURIComponent(name) + "=" + encodeURIComponent(value) + "&";  
            }  
        }  
        return query.length ? query.substr(0, query.length - 1) : query;  
    };  
    $httpProvider.defaults.transformRequest = [function (data) {  
        return angular.isObject(data) && String(data) !== "[object File]" ? param(data) : data;  
    }];  
});  
 
var input_meter = '<?=$id?>';


    app.controller('deviceCtrl',
        function ($scope, $http, $interval , $timeout) {

            $scope.meters = [];   
            $scope.meter = {};     
            $scope.getMeterType = function(type){
                if( type == undefined || type == '' || type == null )
                    return '物理';
                if( type == 'V' )
                    return '虚拟';
                else if( type == 'P')
                    return '物理';
                else
                    return type;
            }

            <?php if($virtual) { ?>

            $scope.getRefMeters  = function (meter) {
                if( !meter )
                    return ;
                var url = '/meter/rest/disp.php?m=virmeters'  ;
                // var url = "/rest/api/data/devRT?" ;

                url = _appendUrlList( url, "id" , meter );
                     
                $http.get( url )
                    .success(
                        function(response) 
                        {
                            response_status( 'get meters :' + meter  ,  response );
                            $scope.meters = response.result;
                             
 
                             
                        }
                );
            };

            <?php } ?>
            
            $scope.getMeter  = function (meter) {
                if( !meter )
                    return ;
                var url = '/meter/rest/disp.php?m=meter'  ;
                // var url = "/rest/api/data/devRT?" ;

                url = _appendUrlList( url, "meter" , meter );
                     
                $http.get( url )
                    .success(
                        function(response) 
                        {
                            response_status( 'get meter :' + meter  ,  response );
                            $scope.meter = response.result;
                            <?php if($virtual) { ?>
                            if($scope.meter._METERTYPE=='V') {
                                $scope.getRefMeters( meter );
                            }                             
                            <?php } ?>
                            $('#_INPUT_METERID').attr('readonly','readonly');

                            if( $scope.meter._TAGS ) {

                              
                                $timeout((function() {
                                        bindTags( $scope.meter._TAGS );
                                }), 0);
                            }
                        }
                );
            };

            $scope.checkUser = function( uid , exist , noexist ){
                var url = '/meter/rest/disp.php?m=usercheck'  ;
                // var url = "/rest/api/data/devRT?" ;

                url = _appendUrlList( url, "user" , uid );
                     
                $http.get( url )
                    .success(
                        function(response) 
                        {
                            response_status( 'checkuser :' + uid  ,  response );
                            var find = response.result;
                            if( find == 1 ){
                                exist(uid);
                            }else if(find == 0 ){
                                noexist(uid);
                            }else {
                                // ???
                                alert( "unkown result " + find 
                                    );
                            }
                        }
                );
         
            }

            $scope.save = function () {
                if (! $scope.meter._METER ) {
                    layer.tips('METER 不能为空' , '#_INPUT_METERID' ,{
                            tips: 4
                        });
                    return ;
                }

                if (! $scope.meter._NAME ) {
                    layer.tips(' NAME 不能为空' , '#_INPUT_NAME' ,{
                           // tips: 4
                        });
                    return ;
                }

                


                var readonly = $('#_INPUT_METERID').attr('readonly');
                if( readonly ) {
                    $scope.saveRaw();
                }else {
                    // $scope.checkUser( $scope.user._USERID , function(u){
                        
                    //     layer.tips('UserId ' + u + '已经存在了' , '#_INPUT_METERID' ,{
                    //         tips: 4
                    //     });
                    // } , 
                    // function(u){
                    //     $scope.saveRaw();
                    // });
                }
            }  
          
            $scope.saveRaw = function () {
                 
                var stags = $('#tags').val() ;

                var url = '/meter/rest/disp.php?m=metersave'  ;
                // var url = "/rest/api/data/devRT?" ;
                var meter = $scope.meter._METER ;
                var name =   $scope.meter._NAME ? $scope.meter._NAME : '';
               
                $http.post( url ,{
                        "meter" : meter , 
                        "name" : name , 
                       
                        "tags" : stags 
                    } )
                    .success(
                        function (response) {
                            response_status( 'save meter :' + meter  ,  response ); 
                            if (response.status != 0) {
                                return;
                            }
                           
                            $scope.getMeter(meter);

                            
                        }
                    );
            };

            $scope.getMeter(input_meter);

            //   

        });
    
    function bindTags(value){
        var tags = $('#tags');
        tags.importTags(value);

        // var list = value.split(",");
        // for( var val in list)
        //     tags.addTag( val );
    }
     $('.tags').tagsInput({width:'100%'});


    function selectFile(){
       $('#uploadFile').click();
    }



    function reloadUnit(  ){
        var ctrl = angular.element('#deviceCtrl');
        var $scope= ctrl.scope();
 
        $scope.getUnit(unitId);
    }

 
    function response_status( command , result ){
        if(result.status == 0 ){
            $('#responseId').removeClass('label-warning');
            $('#responseId').addClass('label-success');
            $('#responseId').text( 'success! ' + command);
        }else {
            $('#responseId').removeClass('label-success');
            $('#responseId').addClass('label-warning');
            
            $('#responseId').text( 'Error : ' + result.status + ' ' + result.message + '\n' + command );
        }
    }
    
     

</script>
</html>
